package com.ruoyi.web.controller.pc.user;

import com.ruoyi.blogs.domain.BsUserFollow;
import com.ruoyi.blogs.service.IBsUserFollowService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api(tags = "关注粉丝")
@RestController
@RequestMapping("/user/follow")
public class UserUserFollowController extends BaseController {
    @Autowired
    private IBsUserFollowService bsUserFollowService;

    @Autowired
    private SysUserMapper userMapper;

    /**
     * 关注或取消关注
     */
    @ApiOperation("关注或取消关注")
    @Transactional
    @PostMapping
    public R<Integer> follow(@RequestBody BsUserFollow bsUserFollow){
        SysUser sysUser = new SysUser();
        sysUser.setUserId(bsUserFollow.getFollowedUserId());
        sysUser.setFansNum(bsUserFollow.getStatus());
        sysUser.setSearchValue("1");
        // 更新粉丝数
        userMapper.updateUserNum(sysUser);
        // 更新关注数
        sysUser.setFansNum(null);
        sysUser.setFollowNum(bsUserFollow.getStatus());
        sysUser.setUserId(SecurityUtils.getUserId());
        userMapper.updateUserNum(sysUser);
        bsUserFollow.setUserId(SecurityUtils.getUserId());
        BsUserFollow follow = new BsUserFollow();
        follow.setUserId(SecurityUtils.getUserId());
        follow.setFollowedUserId(bsUserFollow.getFollowedUserId());
        // 查询是否已有数据
        List<BsUserFollow> list = bsUserFollowService.selectBsUserFollowList(follow);
        if(list.size() > 0){
            bsUserFollow.setId(list.get(0).getId());
            bsUserFollowService.updateBsUserFollow(bsUserFollow);
        } else {
            bsUserFollowService.insertBsUserFollow(bsUserFollow);
        }
        return R.ok();
    }
}
